/*
* @Author: JINPENG
* @Date:   2018-06-23 15:13:12
* @Last Modified by:   JINPENG
* @Last Modified time: 2018-09-06 21:51:08
*/
'use strict';
require('./index.css');
require('page/common/nav-simple/index.js');
var _user   = require('service/user-service.js');
// 表单里的错误提示
var formError = {
    show : function(errMsg){
        $('.error-item').show().find('.err-msg').text(errMsg);
    },
    hide : function(){
        $('.error-item').hide().find('.err-msg').text('');
    }
};
var page = {
		data :{
			username : '',
			question : '',
			answer   : '',
			token	 : ''
		},
		init : function(){
			this.onLand();
			this.bindEvent();
		},
		onLand    : function(){
			this.loadStepUsername();
		},
		bindEvent : function(){
			var _this = this;
			//输入用户名的下一步点击
			$('#username-submit').click(function(){
				var username = $.trim($('#username').val());
				if (username) {
					_user.getQuestion(username,function(res){
						_this.data.username = username;
						_this.data.question = res;
						_this.loadStepQuestion();
					},function(errMsg){
						formError.show(errMsg);
					});
				}
				//未输用户名
				else{
					formError.show('请输入用户名');
				}
			});
			$('#question-submit').click(function(){
				var answer = $.trim($('#answer').val());
				if (answer) {
					_user.checkAnswer({
						username : _this.data.username,
						question : _this.data.question,
						answer   : answer
					},function(res){
						_this.data.answer = answer;
						_this.data.token  = res;
						_this.loadStepPassword();
					},function(errMsg){
						formError.show(errMsg);
					});
				}
				//未输密码提示答案
				else{
					formError.show('请输入密码提示答案');
				}
			});
			$('#password-submit').click(function(){
				var password = $.trim($('#password').val());
				if (password && password.length >=6) {
					_user.resetPassword({
						username : _this.data.username,
						passwordNew : password,
						forgetToken : _this.data.token
					},function(res){
						 window.location.href = './result.html?type=pass-reset';
					},function(errMsg){
						formError.show(errMsg);
					});
				}
				//未输密码
				else{
					formError.show('请输入不少于6位的新密码');
				}
			});
	},
	loadStepUsername : function(){
		$('.step-username').show();
	},
	loadStepQuestion : function(){
		//清除错误提示
		formError.hide();
		//做容器的切换
		$('.step-username').hide()
			.siblings('.step-question').show()
			.find('.question').text(this.data.question);
	},
	loadStepPassword : function(){
	//清除错误提示
	formError.hide();
	$('.step-question').hide().siblings('.step-answer').show();
	}
};
$(function(){
	page.init();
});